# -*- coding:utf-8 -*-

from pydantic import BaseModel
from fastapi import Depends, Request, HTTPException, status

from core.exceptions import ServiceException

from utils.password import password_hash, virify_password
from utils.dependence import PageFilter

from crud.attachment import AttachmentDao
from services.base import BaseService
from schemas.attachment import Attachment, AttachmentCreate


class AttachmentService(BaseService):
    def __init__(self, dao = Depends(AttachmentDao)):
        self.dao = dao
        self.SCHEMA = Attachment

    async def create(self, request: Request, data: AttachmentCreate):
        check_data = await self.dao.first(AttachmentCreate.from_orm({'name': data.name, 'hash': data.hash}))
        # 同名同hash文件
        if check_data is not None:
            return check_data
        # 同hash文件,已上传
        check_data = await self.dao.first(AttachmentCreate.from_orm({'hash': data.hash, 'status': 2}))
        create_user = self.get_current_user(request).id
        if check_data:
            return await self.dao.add(self.SCHEMA(**data.dict(), url= check_data.url, status=2, create_user=create_user))
        
        # 新建文件
        return await self.dao.add(self.SCHEMA(**data.dict(), status=1, create_user=create_user))